package com.ruoyi.msg.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.msg.domain.MsgQa;
import com.ruoyi.msg.domain.bo.MsgQaBo;
import com.ruoyi.msg.domain.vo.MsgQaVo;
import com.ruoyi.msg.mapper.MsgQaMapper;
import com.ruoyi.msg.service.IMsgQaService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 答疑解惑Service业务层处理
 *
 * @author xiaohao
 * @date 2023-02-01
 */
@RequiredArgsConstructor
@Service
public class MsgQaServiceImpl implements IMsgQaService {

    private final MsgQaMapper baseMapper;

    /**
     * 查询答疑解惑
     */
    @Override
    public MsgQaVo queryById(Long id) {
        MsgQaVo result = baseMapper.selectVoById(id);
        renderReplies(Lists.newArrayList(result));
        return result;
    }

    /**
     * 查询答疑解惑列表
     */
    @Override
    public TableDataInfo<MsgQaVo> queryPageList(MsgQaBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MsgQa> lqw = buildQueryWrapper(bo);
        Page<MsgQaVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        renderReplies(result.getRecords());
        return TableDataInfo.build(result);
    }



    /**
     * 查询答疑解惑列表
     */
    @Override
    public List<MsgQaVo> queryList(MsgQaBo bo) {
        LambdaQueryWrapper<MsgQa> lqw = buildQueryWrapper(bo);
        List<MsgQaVo> result = baseMapper.selectVoList(lqw);
        renderReplies(result);
        return result;
    }

    private void renderReplies(List<MsgQaVo> result) {
        List<Long> qaIds = result.stream().map(MsgQaVo::getId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(qaIds)) {
            List<MsgQaVo> replies = baseMapper.selectVoList(Wrappers.<MsgQa>lambdaQuery().in(MsgQa::getReplyId, qaIds));
            Map<Long, List<MsgQaVo>> replyMap = replies.stream().collect(Collectors.groupingBy(MsgQaVo::getReplyId));
            result.forEach(qa -> {
                if (replyMap.containsKey(qa.getId())) {
                    List<MsgQaVo> repliesOfThisQa = replyMap.get(qa.getId());
                    repliesOfThisQa.sort(Comparator.comparing(MsgQaVo::getCreateTime));
                    qa.setReplies(repliesOfThisQa);
                }
            });
        }
    }

    private LambdaQueryWrapper<MsgQa> buildQueryWrapper(MsgQaBo bo) {
        LambdaQueryWrapper<MsgQa> lqw = Wrappers.lambdaQuery();
        lqw.isNull(MsgQa::getReplyId);
        lqw.eq(StringUtils.isNotBlank(bo.getType()), MsgQa::getType, bo.getType());
        return lqw;
    }

    /**
     * 新增答疑解惑
     */
    @Override
    public Boolean insertByBo(MsgQaBo bo) {
        MsgQa add = BeanUtil.toBean(bo, MsgQa.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改答疑解惑
     */
    @Override
    public Boolean updateByBo(MsgQaBo bo) {
        MsgQa update = BeanUtil.toBean(bo, MsgQa.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MsgQa entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除答疑解惑
     */
    @Override
    @Transactional
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        baseMapper.delete(Wrappers.<MsgQa>lambdaQuery().in(MsgQa::getReplyId, ids));
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
